package _剑指offer.二叉树;

import util.TreeNode;
import org.junit.Test;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 交换节点的 左右子树
 * 输入：root = [4,2,7,1,3,6,9]
 * 输出：[4,7,2,9,6,3,1]
 */
public class _27_二叉树的镜像 {
    @Test
    public void main() {
        Integer[] input = new Integer[] {4,2,7,1,3,6,9};
        TreeNode root = TreeNode.getTreeFromArray(input);
        TreeNode.printTree(root);
        TreeNode.printTree(mirrorTree1(root));
    }
    
    public TreeNode mirrorTree1(TreeNode root) {
        if (root == null) return root;
        TreeNode temp = root.left;
        root.left = mirrorTree1(root.right);
        root.right = mirrorTree1(temp);
        return root;
    }
    
    @Test
    public void main2() {
        Integer[] input = new Integer[] {4,2,7,1,3,6,9};
        TreeNode root = TreeNode.getTreeFromArray(input);
        TreeNode.printTree(root);
        TreeNode.printTree(mirrorTree2(root));
    }
    
    public TreeNode mirrorTree2(TreeNode root) {
        if (root == null) return root;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
        }
        return root;
    }
    
}
